
<!-- 数据关联弹窗 -->
<modal-copy-data>
  <utils-modal ref="modal" w="640" h="520" top="15%">
    <yield to="title">选择数据源</yield>
    <yield to="content">
      <div class="community">
        <!-- 切换选取内容来源 -->
        <p>
          <label>
            <input name="type" onclick="{parent.fn.changeType}" ref="activities" type="radio" checked="{parent.type=='activities'}">
            社群活动
          </label>
          <label>
            <input name="type" onclick="{parent.fn.changeType}" ref="articles" type="radio" checked="{parent.type=='articles'}">
            社群文章
          </label>
        </p>

        <table class="base" width="100%">
          <thead>
            <tr>
              <th>选中</th>
              <th>标题</th>
              <th width="35%">{
                parent.type=='articles' ?
                '创建时间' : '开始时间'
              }</th>
            </tr>
          </thead>
          <tbody>
            <tr each="{parent.itemList}">
              <td>
                <input onclick="{parent.parent.fn.checkItem}" type="{parent.parent.fn.multiple()}" name="items">
              </td>
              <td>
                <a href="https://h5.sosho.cn/{parent.parent.type=='articles' ? 'article' : 'activity'}/detail.html?id={id}" target="_blank">{title}</a>
                <span if="{parent.parent.type=='activities'}">{status.name}</span>
              </td>
              <td>{
                parent.parent.type=='articles' ?
                created_at : start_date
              }</td>
            </tr>
          </tbody>
        </table>

        <pagination-number pages="{parent.pages}" page="{parent.page}" on-change="{parent.fn.getList}"/>
      </div>
    </yield>
    <yield to="button">
      <button type="button" onclick="{parent.fn.ok}"  class="btn-main">确定获取</button>
    </yield>
    <yield to="close">取消</yield>
  </utils-modal>

  <script>
  var tag = this;
  var checkedList = [];
  tag.itemList = [];
  tag.type = 'activities';
  tag.page = 1;
  tag.pages = 1;
  tag.fn = {
    openModal: function(){
      tag.refs.modal.fn.open();
      tag.fn.getList();
    },
    ok: function(){
      opts.onOk &&
      opts.onOk(checkedList);
      tag.refs.modal.fn.close();
    },
    multiple: function(){
      // 返回是否需要支持多选
      return ['list'].indexOf(opts.type) !== -1 ? 'checkbox':'radio';
    },
    checkItem: function(e){
      var item = e.item;
      item.type = tag.type;
      item.link = 'https://h5.sosho.cn/'+(tag.type=='articles' ? 'article' : 'activity')+'/detail.html?id='+item.id;
      item.time = tag.type=='articles' ? e.item.created_at : e.item.start_date;
      if(e.target.checked){
        if(tag.fn.multiple() === 'checkbox'){
          checkedList.push(item);
        }
        else{
          checkedList[0] = item;
        }
      }
      if(!e.target.checked){
        checkedList.splice(checkedList.indexOf(e.item), 1);
      }
    },
    changeType: function(e){
      tag.type =
      tag.refs.modal.refs.activities.checked ? 'activities' : 'articles';
      tag.fn.getList();
    },
    getList: function(n){
      if(n && n != tag.page) tag.page = n;
      tag.app.api('GET', 'community/'+tag.type, {
        page: tag.page,
        per_page: 6,
        com_id: 1
      }).on('done', function(resp){
        tag.itemList = resp.data.items;
        tag.pages = resp.data.counts.total_page;
        tag.update();
      });
    }
  };
  tag.on('mount', function(){

  });
  </script>

</modal-copy-data>

<!-- 邮件模块内容 -->
<mail-module-item>

  <virtual each="{c in item.content}">
    <!-- 图片 -->
    <img style="{c._style}" if="{c.type=='img'}" src="{c.value}"/>

    <!-- 文本 -->
    <div style="{c._style}" data-is="utils-raw" if="{c.type=='text'}" content="{c.value}"/>

    <!-- 列表 -->
    <ul style="{c._style}" if="{c.type=='list'}">
      <li each="{v in c.value}">
        [{v.time}]<a style="{c._style_link}" href="{v.link}">{v.title}</a>
      </li>
    </ul>

  </virtual>

  <script>
  var tag = this;
  tag.item = opts.item;
  tag.fn = {
    renderStyle: function(){
      // 设置默认样式
      tag.item.content.forEach(function(c, i){
        var styles = {}, str = '', link = '';
        if(pip.typeOf(c.styles) === 'Array'){
          c.styles.forEach(function(key){
            styles[key] = pip.objDataCopy(
              tag.app.data.global.defaultStyle[key]
            );
          });
          tag.item.content[i].styles = styles;
        }
        // 设置style string
        Object.keys(c.styles).forEach(function(key){
          if(key === 'link'){
            link += 'color: ' + c.styles.link.c + ';';
            link += 'text-decoration: ' + c.styles.link.d + ';';
            tag.item.content[i]._style_link = link;
          }
          if(key === 'size'){
            str += 'width: ' + c.styles.size.w + (c.styles.size.w != 'auto'?'px;':';');
            str += 'height: ' + c.styles.size.h + (c.styles.size.h != 'auto'?'px;':';');
          }
          if(key === 'font'){
            str += 'font-size: ' + c.styles.font.s + ';';
            str += 'font-weight: ' + c.styles.font.w + ';';
            str += 'font-family: ' + c.styles.font.f + ';';
            str += 'text-align: ' + c.styles.font.a + ';';
            str += 'line-height: ' + c.styles.font.l + ';';
            str += 'color: ' + c.styles.font.c + ';';
          }
          if(key === 'float'){
            str += 'float: ' + c.styles.float + ';';
          }
          if(key === 'bg'){
            str += 'background-color: ' + c.styles.bg.c + ';';
          }
          if(key === 'list'){
            str += 'list-style: ' + c.styles.list.t + ';';
            str += 'list-style-position: ' + c.styles.list.p + ';';
          }
          if(key === 'border'){
            str += 'border-top: ' + c.styles.border.t.w + 'px ' + c.styles.border.t.s + ' ' + c.styles.border.t.c + ';';
            str += 'border-right: ' + c.styles.border.r.w + 'px ' + c.styles.border.r.s + ' ' + c.styles.border.r.c + ';';
            str += 'border-bottom: ' + c.styles.border.b.w + 'px ' + c.styles.border.b.s + ' ' + c.styles.border.b.c + ';';
            str += 'border-left: ' + c.styles.border.l.w + 'px ' + c.styles.border.l.s + ' ' + c.styles.border.l.c + ';';
          }
          if(key === 'padding'){
            str += 'padding: ' + c.styles.padding.t + 'px ' + c.styles.padding.r + 'px ' + c.styles.padding.b + 'px ' + c.styles.padding.l + 'px;';
          }
          if(key === 'margin'){
            str += 'margin: ' + c.styles.margin.t + 'px ' + c.styles.margin.r + 'px ' + c.styles.margin.b + 'px ' + c.styles.margin.l + 'px;';
          }
        });
        tag.item.content[i]._style = str;
      });
    }
  };
  tag.on('mount', function(){
    tag.fn.renderStyle();
  });
  tag.on('update', function(){
    tag.fn.renderStyle();
  });
  </script>
</mail-module-item>

<!-- 邮件模块 -->
<mail-module>

  <div class="module {name} {dropable: dropable}">
    <div ref="module" class="sortable-container" style="
      margin: {styles.margin.t}px {styles.margin.r}px {styles.margin.b}px {styles.margin.l}px;
      padding: {styles.padding.t}px {styles.padding.r}px
      {styles.padding.b}px {styles.margin.l}px;
      clear: both; overflow: hidden; float: none;
    ">
      <!-- 内容区块 -->
      <div class="item" each="{item in items}">
        <div class="bar">
          <i class="drag-handle icon-move"></i>
          <i class="edit-handle icon-edit-alt" onclick="{fn.editItem}"></i>
          <i class="remove-handle icon-trash" onclick="{fn.removeItem}"></i>
        </div>
        <!-- 模块内容 -->
        <div data-is="mail-module-item" item="{item}"></div>
      </div>
      <!-- 没有内容提示 -->
      <span class="empty item" if="{items.length==0}">
        没有内容，可拖拽模块到这里进行添加。
      </span>
    </div>
  </div>

  <script>
  var tag = this;
  tag.name = opts.name;
  tag.styles = opts.styles || {};
  tag.items = opts.items || [];

  tag.fn = {
    // 编辑内容模块
    editItem: function(e){
      tag.opts.onEdit && tag.opts.onEdit(e.item.item, tag);
    },
    // 删除内容模块
    removeItem: function(e){
      tag.items.splice(tag.items.indexOf(e.item.item), 1);
      tag.opts.onRemove && tag.opts.onRemove();
    },
    // 激活sortable
    // https://github.com/RubaXa/Sortable
    sortable: function(){
      new Sortable(tag.refs.module, {
        group: { name: 'module', put: ['items'] },
        animation: 150,
        handle: '.drag-handle',
        draggable: '.item',
        onUpdate: function(e){
          pip.arr.move(tag.items, e.oldIndex, e.newIndex);
          opts.onUpdate && opts.onUpdate();
        },
        onAdd: function(e){
          var index = [].slice.call(
            tag.refs.module.children
          ).indexOf(e.item);
          tag.refs.module.removeChild(e.item);
          opts.onAdd && opts.onAdd(tag, index);
        }
      });
    }
  };

  tag.on('mount', function(){
    tag.fn.sortable();
  });

  tag.on('item::add', function(item, index){
    var items = pip.objDataCopy(tag.app.data.global.items);
    tag.items.push(items[item.name]);
    pip.arr.move(tag.items, tag.items.length-1, index);
    tag.update();
  });
  </script>

</mail-module>


<!-- 模块内容集合 -->
<mail-module-items>

  <div ref="items">
    <div class="item" each="{item in items}">
      <div class="drag-hide icon icon-{item.name}"></div>
      <div class="drag-hide text">{item.text}</div>
      <div class="drag-show">添加到这里</div>
    </div>
  </div>

  <script>
    var tag = this;
    tag.items = [
      {name: 'text', text: '文本'},
      {name: 'list', text: '列表'},
      {name: 'img_text', text: '图文'}
    ];
    tag.fn = {
      // 激活sortable
      // https://github.com/RubaXa/Sortable
      sortable: function(){
        new Sortable(tag.refs.items, {
          group: { name: 'items', pull: ['clone'] },
          animation: 150,
          sort: false,
          draggable: '.item',
          onStart: function(e){
            tag.emit('drag::start', e);
          },
          onEnd: function(e){
            tag.emit('drag::end', tag.items[e.oldIndex]);
          }
        });
      }
    };
    tag.on('mount', function(){
      tag.fn.sortable();
    });
  </script>
</mail-module-items>


<!-- 邮件编辑 -->
<mail-edit>
  <!-- 邮件内容编辑区 -->
  <div class="editor">
    <div ref="mail" class="mail">
      <!-- 布局单列 -->
      <div if="{mail.layout=='onecol'}" class="onecol">
        <mail-module class="{m.name}" styles="{m.styles}" each="{m in mail.modules}" items="{m.items}" on-add="{parent.fn.addModuleItem}" on-edit="{parent.fn.editModuleItem}" on-remove="{parent.fn.removeModuleItem}" on-update="{parent.fn.saveMail}"/>
      </div>
    </div>
  </div>

  <!-- 内容操作区域 -->
  <div class="toolbox">
    <div if="{!item.type}" class="section">
      <h2>模块区</h2>
      <mail-module-items ref="items"/>
    </div>
    <div if="{item.type}" class="section">
      <ul class="tab">
        <li onclick="{fn.changeTab}" each="{itemTabList}" onclick="{fn.onTab}" class="{active: itemTab==name}">{text}</li>
      </ul>
      <!-- 编辑内容 -->
      <div show="{itemTab=='content'}">
        <div class="content-{c.type}" each="{c in item.content}">
          <!-- 文本 -->
          <tinymce-editor ref="tinymce" if="{c.type=='text'}" on-update="{fn.updateContentText}" w="90%" h="400px" content="{c.value}" item="{c}"/>
          <!-- 图片 -->
          <div if="{c.type=='img'}">
            图片
            <qiniu-upload if="{qiniuToken}" accept=".jpg,.gif,.png" token="{qiniuToken}" domain="{uploadDomain}" on-success="{fn.imgUploaded}" folder="{app.data.env}/temp" item="{c}"/>
          </div>
          <!-- 列表 -->
          <div ref="listItems" if="{c.type=='list'}">
            <p class="list-sortable-item" each="{v in c.value}">
              标题 <input type="text" onkeyup="{fn.updateListItem}" name="title" value="{v.title}">
              时间 <input type="text" onkeyup="{fn.updateListItem}" name="time"  value="{v.time}">
              链接 <input type="text" onkeyup="{fn.updateListItem}" name="link" value="{v.link}">
              <button type="button" onclick="{fn.removeListItem}">-</button>
            </p>
            <p>
              标题 <input type="text" ref="listTitle">
              时间 <input type="text" ref="listTime">
              链接 <input type="text" ref="listLink">
              <button type="button" onclick="{fn.addListItem}">+</button>
            </p>
          </div>
        </div>
        <modal-copy-data ref="dataModal" on-ok="{fn.getDataFromModal}" type="{item.type}"/>
        <button type="button" onclick="{fn.openDataModal}">社群数据</button>
      </div>
      <!-- 内容样式 -->
      <div show="{itemTab=='style'}">
        <div class="content-{c.type}-style" each="{c in item.content}">
          <h4 if="{item.content.length>1}">
            {contentTypes[c.type]}
          </h4>
          <!-- 链接 -->
          <div if="{c.styles.link}" class="link-set">
            链接颜色
            <input-color v="{c.styles.link.c}" on-change="{parent.fn.linkColor}" item="{c}"/>
            <label>
              <input type="checkbox" onclick="{fn.linkLine}" checked="{c.styles.link.d=='underline'}">
              下划线
            </label>
          </div>
          <!-- 宽高 -->
          <div if="{c.styles.size}" class="size-set">
            宽 <span>{c.styles.size.w}</span>
            <input oninput="{fn.widthSize}" type="range" min="10" max="1200" step="10" value="{c.styles.size.w}">
            <br>
            高 <span>{c.styles.size.h}</span>
            <input oninput="{fn.heightSize}" type="range" min="10" max="1200" step="10" value="{c.styles.size.h}">
          </div>
          <!-- 浮动 -->
          <div if="{c.styles.float}" class="float-set">
            浮动
            <select onchange="{fn.float}">
              <option value="{name}" each="{[{name:'left',text:'靠左'},{name:'right',text:'靠右'},{name:'none',text:'无'}]}" selected="{name==c.styles.float}">{text}</option>
            </select>
          </div>
          <!-- 列表 -->
          <div if="{c.styles.list}" class="list-set">
            列表样式
            <select onchange="{fn.listType}">
              <option value="{name}" each="{listType}" selected="{name==c.styles.list.t}">{text}</option>
            </select>
            <label>
              <input type="radio" name="list-position" value="inside"  onclick="{fn.listPos}" checked="{c.styles.list.p=='inside'}">
              靠内
            </label>
            <label>
              <input type="radio" name="list-position" value="outside" onclick="{fn.listPos}" checked="{c.styles.list.p=='outside'}">
              靠外
            </label>
          </div>
          <!-- 字体 -->
          <div if="{c.styles.font}" class="font-set">
            文字大小 <span>{c.styles.font.s}</span>
            <input oninput="{fn.fontSize}" type="range" min="12" max="48" step="1" value="{parseInt(c.styles.font.s)}">
            <br>
            文字颜色
            <input-color v="{c.styles.font.c}" on-change="{parent.fn.fontColor}" item="{c}"/>
            <br>
            文字粗细
            <select onchange="{fn.fontWeight}">
              <option value="{name}" each="{fontWeight}" selected="{name==c.styles.font.w}">{text}</option>
            </select>
            <br>
            文字对齐
            <select onchange="{fn.fontAlign}">
              <option value="{name}" each="{fontAlign}" selected="{name==c.styles.font.a}">{text}</option>
            </select>
            <br>
            文字行高<span>{c.styles.font.l}</span>
            <input oninput="{fn.fontLH}" type="range" min="100" max="300" step="10" value="{parseInt(c.styles.font.l)}">
            <br>
            字体
            <select onchange="{fn.fontFamily}">
              <option value="{name}" each="{fontFamily}" selected="{name==c.styles.font.f}">{text}</option>
            </select>
          </div>
          <!-- 边框 -->
          <div if="{c.styles.border}" class="border-set">
            <div class="top">
              上边框粗 <span>{c.styles.border.t.w}px</span>
              <input oninput="{fn.borderTW}" type="range" min="0" max="10" step="1" value="{c.styles.border.t.w}">
              <br>
              边框颜色
              <input-color v="{c.styles.border.t.c}" on-change="{parent.fn.borderTC}" item="{c}"/>
            </div>
            <div class="bottom">
              下边框粗 <span>{c.styles.border.b.w}px</span>
              <input oninput="{fn.borderBW}" type="range" min="0" max="10" step="1" value="{c.styles.border.b.w}">
              <br>
              边框颜色
              <input-color v="{c.styles.border.b.c}" on-change="{parent.fn.borderBC}" item="{c}"/>
            </div>
            <div class="left">
              左边框粗 <span>{c.styles.border.l.w}px</span>
              <input oninput="{fn.borderLW}" type="range" min="0" max="10" step="1" value="{c.styles.border.l.w}">
              <br>
              边框颜色
              <input-color v="{c.styles.border.l.c}" on-change="{parent.fn.borderLC}" item="{c}"/>
            </div>
            <div class="right">
              右边框粗 <span>{c.styles.border.r.w}px</span>
              <input oninput="{fn.borderRW}" type="range" min="0" max="10" step="1" value="{c.styles.border.r.w}">
              <br>
              边框颜色
              <input-color v="{c.styles.border.r.c}" on-change="{parent.fn.borderRC}" item="{c}"/>
            </div>
          </div>
          <!-- 内间距 -->
          <div if="{c.styles.padding}" class="padding-set">
            <div class="top">
              上内间距 <span>{c.styles.padding.t}px</span>
              <input oninput="{fn.paddingTop}" type="range" min="0" max="200" step="1" value="{c.styles.padding.t}">
            </div>
            <div class="bottom">
              下内间距 <span>{c.styles.padding.b}px</span>
              <input oninput="{fn.paddingBottom}" type="range" min="0" max="200" step="1" value="{c.styles.padding.b}">
            </div>
            <div class="left">
               左内间距 <span>{c.styles.padding.l}px</span>
              <input oninput="{fn.paddingLeft}" type="range" min="0" max="200" step="1" value="{c.styles.padding.l}">
            </div>
            <div class="right">
               右内间距 <span>{c.styles.padding.r}px</span>
              <input oninput="{fn.paddingRight}" type="range" min="0" max="200" step="1" value="{c.styles.padding.r}">
            </div>
          </div>
          <!-- 外间距 -->
          <div if="{c.styles.margin}" class="margin-set">
            <div class="top">
              上外间距 <span>{c.styles.margin.t}px</span>
              <input oninput="{fn.marginTop}" type="range" min="0" max="200" step="1" value="{c.styles.margin.t}">
            </div>
            <div class="bottom">
              下外间距 <span>{c.styles.margin.b}px</span>
              <input oninput="{fn.marginBottom}" type="range" min="0" max="200" step="1" value="{c.styles.margin.b}">
            </div>
            <div class="left">
               左外间距 <span>{c.styles.margin.l}px</span>
              <input oninput="{fn.marginLeft}" type="range" min="0" max="200" step="1" value="{c.styles.margin.l}">
            </div>
            <div class="right">
               右外间距 <span>{c.styles.margin.r}px</span>
              <input oninput="{fn.marginRight}" type="range" min="0" max="200" step="1" value="{c.styles.margin.r}">
            </div>
          </div>
          <!-- 背景 -->
          <div if="{c.styles.bg}" class="bg-set">
            <div class="color">
              背景颜色
              <input-color v="{c.styles.bg.c}" on-change="{parent.fn.bgColor}" item="{c}"/>
            </div>
          </div>
        </div>
      </div>
      <p>
        <button type="button" onclick="{fn.saveModuleItem}">确定</button>
      </p>
    </div>
  </div>

  <script>
  var tag = this;
  tag.uploadDomain = 'http://7xwb9d.com2.z0.glb.qiniucdn.com';
  tag.contentTypes = {
    text: '文本内容', list: '列表信息', img: '图片'
  };
  tag.mail = {
    id: tag.app.path[2]
  };
  // 内容编辑器
  tag.item = {};
  tag.itemTabList = [
    {name: 'content', text: '内容编辑'},
    {name: 'style', text: '内容样式'}
  ];
  tag.fontAlign = tag.app.data.global.fontAlign;
  tag.fontWeight = tag.app.data.global.fontWeight;
  tag.fontFamily = tag.app.data.global.fontFamily;
  tag.listType = tag.app.data.global.listType;
  tag.itemTab = 'content';
  tag.fn = {
    removeListItem: function(e){
      tag.item.content[0].value.splice(
        tag.item.content[0].value.indexOf(e.item.v),
        1
      );
    },
    addListItem: function(e){
      tag.item.content[0].value.push({
        title: tag.refs.listTitle.value,
        link: tag.refs.listLink.value,
        time: tag.refs.listTime.value
      });
      tag.refs.listTitle.value =
      tag.refs.listLink.value =
      tag.refs.listTime.value = '';
    },
    // 重数据源获取的数据副本
    getDataFromModal: function(datalist){
      if(tag.item.type === 'list'){
        tag.item.content[0].value =
        tag.item.content[0].value.concat(datalist);
      }
      if(tag.item.type === 'img_text'){
        if(datalist[0].type === 'activities'){
          tag.item.content[0].value =
          '<h4>'+datalist[0].title+'</h4>' +
          '<p><b>介绍:</b>'+datalist[0].intro+'</p>' +
          '<p><b>地点:</b>'+datalist[0].address+'</p>' +
          '<p><b>开始时间:</b>'+datalist[0].start_date+'</p>';
          tag.item.content[1].value = datalist[0].img_path;
          tag.refs.tinymce.fn.setContent(tag.item.content[0].value);
        }
      }
      tag.update();
    },
    // 打开选择数据弹窗
    openDataModal: function(e){
      tag.refs.dataModal.fn.openModal();
    },
    // 更新列表模块内容（手动）
    updateListItem: function(e){
      e.item.v[e.target.name] = e.target.value;
    },
    linkLine: function(e){
      e.item.c.styles.link.d = e.target.checked ? 'underline' : 'none';
    },
    linkColor: function(c, v){
      c.styles.link.c = v;
      tag.update();
    },
    updateList: function(c, list){
      c.value = list;
      tag.update();
    },
    heightSize: function(e){
      e.item.c.styles.size.h = e.target.value;
    },
    widthSize: function(e){
      e.item.c.styles.size.w = e.target.value;
    },
    float: function(e){
      e.item.c.styles.float = e.target.value;
    },
    listPos: function(e){
      e.item.c.styles.list.p = e.target.value;
    },
    listType: function(e){
      e.item.c.styles.list.t = e.target.value;
    },
    bgColor: function(c, v){
      c.styles.bg.c = v;
      tag.update();
    },
    marginTop: function(e){
      e.item.c.styles.margin.t = e.target.value;
    },
    marginBottom: function(e){
      e.item.c.styles.margin.b = e.target.value;
    },
    marginLeft: function(e){
      e.item.c.styles.margin.l = e.target.value;
    },
    marginRight: function(e){
      e.item.c.styles.margin.r = e.target.value;
    },
    paddingTop: function(e){
      e.item.c.styles.padding.t = e.target.value;
    },
    paddingBottom: function(e){
      e.item.c.styles.padding.b = e.target.value;
    },
    paddingLeft: function(e){
      e.item.c.styles.padding.l = e.target.value;
    },
    paddingRight: function(e){
      e.item.c.styles.padding.r = e.target.value;
    },
    fontFamily: function(e){
      e.item.c.styles.font.f = e.target.value;
    },
    fontLH: function(e){
      e.item.c.styles.font.l = e.target.value+'%';
    },
    fontAlign: function(e){
      e.item.c.styles.font.a = e.target.value;
    },
    fontWeight: function(e){
      e.item.c.styles.font.w = e.target.value;
    },
    fontColor: function(c, v){
      c.styles.font.c = v;
      tag.update();
    },
    borderTC: function(c, v){
      c.styles.border.t.c = v;
      tag.update();
    },
    borderTW: function(e){
      e.item.c.styles.border.t.w = e.target.value;
    },
    borderBC: function(c, v){
      c.styles.border.b.c = v;
      tag.update();
    },
    borderBW: function(e){
      e.item.c.styles.border.b.w = e.target.value;
    },
    borderLC: function(c, v){
      c.styles.border.l.c = v;
      tag.update();
    },
    borderLW: function(e){
      e.item.c.styles.border.l.w = e.target.value;
    },
    borderRC: function(c, v){
      c.styles.border.r.c = v;
      tag.update();
    },
    borderRW: function(e){
      e.item.c.styles.border.r.w = e.target.value;
    },
    fontSize: function(e){
      e.item.c.styles.font.s = e.target.value+'px';
    },
    updateContentText: function(c, data){
      c.value = data.edit.getContent();
      tag.update();
    },
    // 保存邮件
    saveMail: function(){
      tag.app.api('POST', 'mail_manage/update_mail', {
        cid: 1,
        template_id: tag.mail.template_id,
        mail_id: tag.mail.id,
        modules: JSON.stringify(tag.mail.modules),
        html: tag.refs.mail.innerHTML,
        subject: tag.mail.subject
      }).on('done', function(resp){
        tag.update();
      });
    },
    // qiniu token
    qiniuToken: function(){
      tag.app.api('GET', 'tool/upload_token', {
        bucket: 'attachments'
      }).on('done', function(resp){
        tag.qiniuToken = resp.data.qiniu_token;
      });
    },
    imgUploaded: function(files, c){
      c.value = files.pop().url;
      tag.update();
    },
    changeTab: function(e){
      tag.itemTab = e.item.name;
    },
    removeModuleItem: function(e){
      tag.item = {};
      tag.fn.saveMail();
    },
    saveModuleItem: function(e){
      tag.item = {};
      tag.fn.saveMail();
    },
    editModuleItem: function(item){
      tag.item = item;
      tag.update();
      if(tag.item.type === 'list'){
        // 如果是列表可以拖拽
        // 激活sortable
        // https://github.com/RubaXa/Sortable
        new Sortable(tag.refs.listItems, {
          group: 'module-list',
          animation: 150,
          draggable: '.list-sortable-item',
          onUpdate: function(e){
            pip.arr.move(tag.item.content[0].value, e.oldIndex, e.newIndex);
            tag.update();
          },
        });
      }
    },
    // TODO: 这块地方的数据传递有点复杂，需要优化
    addModuleItem: function(module, index){
      tag.refs.items.once('drag::end', function(item){
        module.emit('item::add', item, index);
        tag.fn.saveMail();
      });
    },
    getMail: function(){
      tag.app.api('GET', 'mail_manage/mail/view', {
        mail_id: tag.mail.id,
        cid: 1
      }).on('done', function(resp){
        tag.mail = resp.data;
        tag.mail.modules = JSON.parse(tag.mail.modules);
        tag.update();
      });
    }
  };

  tag.on('mount', function(){
    tag.fn.getMail();
    tag.fn.qiniuToken();
  });

  </script>
</mail-edit>

<!-- 新邮件 -->
<mail-new>
  <div class="mail-name">
    邮件名
    <input type="text" onkeyup="{fn.nameInput}">
  </div>
  <div class="mail-tpl">
    内容模板
    <span>{loading}</span>
    <ul>
      <li each="{tpl in tplList}"
          class="{active: mail.tpl==tpl.id}"
          onclick="{fn.select}">
        <img src="{tpl.img_path}">
        <a href="javascript:;">{tpl.name}</a>
      </li>
    </ul>
    <pagination-number pages="{pages}" page="{page}" on-change="{fn.tplList}">
  </div>
  <div class="btn-panel">
    <button type="button" onclick="{fn.startEdit}" disabled="{!fn.isReady()}">确定，开始编辑</button>
    <button type="button" onclick="{fn.goBack}">取消</button>
  </div>

  <script>
    var tag = this;
    tag.mail = {};
    tag.page = tag.app.query.page || 1;
    tag.fn = {
      startEdit: function(e){
        e.target.disabled = true;
        tag.app.api('POST', 'mail_manage/new_mail', {
          template_id: tag.mail.tpl,
          subject: tag.mail.subject,
          cid: 1
        }, {
          trigger: e.target
        })
        .on('done', function(resp){
          route('mail/edit/'+resp.data.id);
        });
      },
      goBack: function(){
        route('mail');
      },
      nameInput: function(e){
        tag.mail.subject = e.target.value;
      },
      isReady: function(){
        return tag.mail.tpl && tag.mail.subject;
      },
      select: function(e){
        tag.mail.tpl = e.item.tpl.id;
      },
      tplList: function(n){
        if(n && n != tag.page){
          return route(tag.app.search({
            page: n
          }));
        }
        tag.app.once('api::start', function(){
          tag.update({
            loading: 'loading..'
          });
        }).once('api::complete', function(){
          tag.update({
            loading: null
          });
        });
        tag.app.api('GET', 'mail_manage/templates', {
          cid: 1, page: n
        })
        .on('done', function(resp){
          tag.update({
            tplList: resp.data.items,
            pages: resp.data.counts.total_page,
            page: resp.data.counts.page
          });
        });
      }
    };
    tag.on('mount', function(){
      tag.fn.tplList(tag.page);
    });
  </script>
</mail-new>

<!-- 邮件列表 -->
<mail-list>
  <div class="mail-list">
    <h2>
      邮件列表
      <a href="#!mail/new">+</a>
    </h2>
    <table class="base">
      <thead>
        <tr>
          <th>邮件主题</th>
          <th>更新时间</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr each="{mail in mailList}">
          <td>
            <a href="javascript:;" onclick="{fn.view}">{mail.subject}</a>
          </td>
          <td>{mail.updated_at}</td>
          <td>
            <a href="javascript:;" onclick="{fn.copy}">复制</a>
            <a href="javascript:;" onclick="{fn.edit}">编辑</a>
            <a href="javascript:;" onclick="{fn.remove}">删除</a>
          </td>
        </tr>
        <tr if="{mailList && !mailList.length}">
          <td colspan="3">没有邮件，请新建</td>
        </tr>
      </tbody>
    </table>
  </div>
  <script>
    var tag = this;
    tag.fn = {
      add: function(){

      },
      remove: function(e){
        tag.app.api('POST', 'mail_manage/del_mails', {
          cid: 1, mail_id: e.item.mail.id
        })
        .on('done', function(resp){
          tag.fn.mailList();
        });
      },
      copy: function(){

      },
      edit: function(e){
        route('mail/edit/'+e.item.mail.id);
      },
      view: function(){

      },
      mailList: function(){
        tag.app.api('GET', 'mail_manage/mails', { cid: 1 })
        .on('done', function(resp){
          tag.update({
            mailList: resp.data.items
          })
        });
      }
    };
    tag.on('mount', function(){
      tag.fn.mailList();
    });
  </script>
</mail-list>


<!-- PAGE -->
<comail-mail>
  <!-- 邮件列表 -->
  <div class="container" data-is="mail-{section}"/>
  <script>
    var tag = this;
    tag.section = tag.app.path[1] || 'list';
    tag.fn = {};
    tag.on('mount', function(){

    });
  </script>
</comail-mail>
